package com.example.demo.controller;

import com.example.demo.dao.AccountRep;
import com.example.demo.dao.CustomerRep;
import com.example.demo.model.Account;
import com.example.demo.model.Customer;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/account")
public class AccountController {

    private final CustomerRep CustomerRep;

    private final AccountRep AccountRep;

    public AccountController(CustomerRep CustomerRep, AccountRep AccountRep) {
        this.CustomerRep = CustomerRep;
        this.AccountRep = AccountRep;
    }

    @PostMapping(value = "/{customerId}/accounts")
    @ResponseStatus(code = HttpStatus.CREATED)
    public Account save(@PathVariable Long customerId, @RequestBody Account account) {
        return CustomerRep.findById(customerId).map(customer -> {

            account.setCustomer(customer);
            return AccountRep.save(account);

        }).orElseThrow(() -> new RuntimeException("Customer [customerId=" + customerId + "] can't be found"));

    }

    @GetMapping(value = "/{customerId}/accounts")
    public Page<Account> all(@PathVariable Long customerId, Pageable pageable) {
        return AccountRep.findByCustomer_CustomerId(customerId, pageable);
    }

    @DeleteMapping(value = "/{customerId}/accounts/{accountId}")
    public ResponseEntity<?> deleteAccount(@PathVariable Long customerId, @PathVariable Long accountId) {

        if (!CustomerRep.existsById(customerId)) {
            throw new RuntimeException("Customer [customerId=" + customerId + "] can't be found");
        }

        return AccountRep.findById(accountId).map(account -> {
            AccountRep.delete(account);
            return ResponseEntity.ok().build();
        }).orElseThrow(() -> new RuntimeException("Account [accountId=" + accountId + "] can't be found"));

    }

    @PutMapping(value = "/{customerId}/accounts/{accountId}")
    public ResponseEntity<Account> updateAccount(@PathVariable Long customerId, @PathVariable Long accountId, @RequestBody Account newAccount) {

        Customer customer = CustomerRep.findById(customerId).orElseThrow(() -> new RuntimeException("Customer [customerId=" + customerId + "] can't be found"));

        return AccountRep.findById(accountId).map(account -> {
            newAccount.setCustomer(customer);
            newAccount.setAccountNumber(accountId);
            AccountRep.save(newAccount);
            return ResponseEntity.ok(newAccount);
        }).orElseThrow(() -> new RuntimeException("Account [accountId=" + accountId + "] can't be found"));


    }
}
